import {
	reFlushcCurrentUser,
	getInfo,
	loginIn,
	logout,
	register
} from '@/api/login/login';
import router from '../../pages/index/router';

const user = {
	state: {
		user: {}
	},

	mutations: {
		LOGIN_SUCCESS: (state, user) => {
			state.user = user;
		},
		LOGOUT_USER: state => {
			state.user = {};
		},
		UPDATE_USER: (state, user) => {
			sessionStorage.setItem('user', JSON.stringify(user));
			let users = JSON.parse(sessionStorage.getItem('user'));
			state.user = (!!users.userId) ? users : {};
		},
	},
	actions: {
		// 手机登录
		LoginAction({commit}, userInfo) {
			return new Promise((resolve, reject) => {
				loginIn(userInfo).then(response => {
					if (response.code === 200) {
						const data = response.data;
						commit('LOGIN_SUCCESS', data);
						loginSuccess();
						resolve(data);
					}
				}).catch(error => {
					reject(error);
				});
			});
		},
		// 获取用户信息
		GetinfoAction({commit, state}) {
			return new Promise((resolve, reject) => {
				getInfo().then(response => {
					const data = response.data;
					commit('LOGIN_SUCCESS', data);
					resolve(response);
				}).catch(error => {
					reject(error);
				});
			});
		},
		// 登出
		LogoutAction({commit, state}) {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					commit('LOGOUT_USER');
					resolve();
				}).catch(error => {
					reject(error);
				});
			});
		},
		RegisterAction({commit, state}, registerForm) {
			return new Promise((resolve, reject) => {
				register(registerForm).then(response => {
					const data = response.data;
					//commit('LOGIN_SUCCESS', data);
					resolve(response);
				}).catch(error => {
					reject(error);
				});
			});
		},
		ClearUser({commit, state}){
			return new Promise((resolve, reject) => {
				commit('LOGOUT_USER');
				sessionStorage.clear();
				resolve();
			});
		}
	}
};
const loginSuccess = () => {
	let params = {};
	let current = router.history.current;
	for (let key in current.query) {
		current.query[key] = decodeURIComponent(current.query[key]);
		if (key != 'path') {
			params[key] = current.query[key]
		}
	}
	router.push({
		path: current.query.path ? current.query.path : '/',
		query: params
	});
}

export default user;
